package com.wwwarehouse.contract.contract;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.adapter.pop.BubblePopAdapter;
import com.wwwarehouse.common.bean.filter.FilterBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.contract.bean.ResourceItemBean;
import com.wwwarehouse.contract.common.ContractCommon;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.event.CountEvent;
import com.wwwarehouse.contract.event.GoodsRefreshEvent;
import com.wwwarehouse.contract.event.ReleaseEvent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/10/19.
 *         <p/>
 *         浏览商品
 */

public class ReleaseGoodsFragment extends MyBaseViewPagerFragment {

    private List<FilterBean> sortList; //排序
    private boolean isShow = true;
    private String mSort = "create_time desc";
    private String pbUkid;
    private String buId;
    private String text;

    private int select;
    private List<ResourceItemBean.DataBean.ListBean> selectTag;
    boolean isRequest = true;

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ReleaseGoodsFragment) {
            mActivity.setTitle("选择商品");
        }
    }

    @Override
    public void requestDatas() {
        EventBus.getDefault().register(this);
        ContractCommon.getInstance().getPublishGoodsData().clear();
        sortList = new ArrayList<>();
        sortList.add(new FilterBean(true, "更新时间由近到远")); //默认排序
        sortList.add(new FilterBean(false, "更新时间由远到近"));
        Bundle bundle = getArguments();
        if (bundle != null) {
            pbUkid = bundle.getString("pbUkid");
            buId = bundle.getString("buId");
            select = bundle.getInt("count");
            mConfirmBtn.setVisibility(select > 0 ? View.VISIBLE : View.GONE);
            mConfirmBtn.setText(select + "");
        }
        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存选择资源
                ((BaseCardDeskActivity) mActivity).hideSearchTitle();
                try {
                    if (getSelectTag().size() == 0) {
                        toSettingRule();
                    } else {
                        if (isRequest) {
                            saveSelectResource(getSelectTag());
                        } else {
                            toSettingRule();
                        }
                    }
                } catch (Exception e) {
                    toSettingRule();
                }


            }
        });
        requestData();

    }

    private void toSettingRule() {
        ReleaseSettingPublishingRulesFragment rulesFragment = new ReleaseSettingPublishingRulesFragment();
        Bundle bundle = new Bundle();
        bundle.putString("pbUkid", pbUkid); //  发布ukid
        bundle.putString("sort", mSort); //   排序(DESC,ASC)
        rulesFragment.setArguments(bundle);
        pushFragment(rulesFragment);
    }

    private void saveSelectResource(List<ResourceItemBean.DataBean.ListBean> selectTag) {
        HashSet<ResourceItemBean.DataBean.ListBean> listBeen = new HashSet<>(selectTag);
        selectTag.clear();
        selectTag.addAll(listBeen);
        Map<String, Object> map = new HashMap<>();
        ArrayList<Map<String, Object>> pbRsItemTempList = new ArrayList<>();
        for (int i = 0; i < selectTag.size(); i++) {
            Map<String, Object> listData = new HashMap<>();
            listData.put("definedName", selectTag.get(i).getDefinedName());
            listData.put("definedUkid", selectTag.get(i).getDefinedUkid());
            try {
                listData.put("identifyCode", selectTag.get(i).getIdentifyList().get(0).getIdentifyCode());
                listData.put("relatedUrl", selectTag.get(i).getMediaList().get(0).getRelatedUrl());
            } catch (Exception e) {
            }
            listData.put("unitName", selectTag.get(i).getUnitName());
            listData.put("unitUkid", selectTag.get(i).getUnitUkid());
            pbRsItemTempList.add(listData);
        }

        map.put("pbRsItemTempList", pbRsItemTempList);
        map.put("pbUkid", pbUkid);
        httpPost(ContractConstant.SAVERESOURCEITEMS, map, 1, true, "");
    }

    private void requestData() {
        Map<String, Object> map = new HashMap<>();
        map.put("buId", buId); //   业务单位ID(必填)
        map.put("page", "1"); //
        map.put("pbUkid", pbUkid); //  发布ukid
        map.put("rsName", ""); // 资源名称
        map.put("size", "5"); //
        map.put("sort", mSort); //     排序(DESC,ASC)
        httpPost(ContractConstant.RESOURCEITEMS, map, 0, false, "");
    }

    public void onEventMainThread(Object event) {
        if (event instanceof ReleaseEvent) {
            if (((ReleaseEvent) event).getMsg().equals("notify")) {
                if (((ReleaseEvent) event).getCode() == ReleaseEvent.RELEASE_SELECT_GOODS) {
                    int selectTagCount = getSelectTag().size();
                    mConfirmBtn.setVisibility(selectTagCount + select > 0 ? View.VISIBLE : View.GONE);
                    mConfirmBtn.setText(selectTagCount + select + "");
                }
            }
        } else if (event instanceof GoodsRefreshEvent) {
            requestData();
        } else if (event instanceof CountEvent) {
            select = ((CountEvent) event).getCount();
            mConfirmBtn.setVisibility(select > 0 ? View.VISIBLE : View.GONE);
            mConfirmBtn.setText(select + "");
        }
    }

    @Override
    public void sortClick(View anchor) {
        //排序
        PopUpUtils.showBubbleDown(anchor, mActivity, sortList, new BubblePopAdapter.OnPopListClickListener() {
            @Override
            public void setOnItemClickListener(int i, View view) {
                if (i == 0) {
                    mSort = "create_time desc";      //时间正序
                    sortList.get(0).setSelect(true);
                    sortList.get(1).setSelect(false);

                } else if (i == 1) {
                    mSort = "create_time asc";        //时间倒序
                    sortList.get(0).setSelect(false);
                    sortList.get(1).setSelect(true);

                }
                requestData();

            }
        });

    }

    @Override
    public void searchNoRealTimeClick(String text) {
        selectTag = getSelectTag();
        this.text = text;
        Map<String, Object> map = new HashMap<>();
        map.put("buId", buId); //   业务单位ID(必填)
        map.put("page", "1"); //
        map.put("pbUkid", pbUkid); //  发布ukid
        map.put("rsName", text); // 资源名称
        map.put("size", "5"); //
        map.put("sort", mSort); //     排序(DESC,ASC)
        httpPost(ContractConstant.RESOURCEITEMS, map, 2, true, "");

    }


    @Override
    public void cancelClick() {
        selectTag = getSelectTag();
        mConfirmBtn.setVisibility(selectTag.size() > 0 ? View.VISIBLE : View.GONE);
        mCustomPager.setVisibility(View.VISIBLE);
        mEmptyLayout.setVisibility(View.GONE);
        requestData();
    }

    //获取选择的数据集合
    private List<ResourceItemBean.DataBean.ListBean> getSelectTag() {
        List<ResourceItemBean.DataBean.ListBean> selectDatas = new ArrayList<>();
        for (int i = 0; i < fragmentList.size(); i++) {
            if (fragmentList.get(i) != null) {
                ReleaseGoodsListFragment currentFragment = (ReleaseGoodsListFragment) fragmentList.get(i);
                if (currentFragment.mAdapter != null) {
                    List<ResourceItemBean.DataBean.ListBean> selectData = currentFragment.mAdapter.getSelectData();
                    selectDatas.addAll(selectData);
                }
            }
        }
        return selectDatas;
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {

        if (what == 0) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                ResourceItemBean.DataBean dataBean = JSON.parseObject(commonClass.getData().toString(), ResourceItemBean.DataBean.class);
                if (dataBean.getTotal() == 0) {
                    ShowEmptyGoodsView();
                    if (selectTag != null) {
                        HashSet<ResourceItemBean.DataBean.ListBean> listBeen = new HashSet<>(selectTag);
                        mConfirmBtn.setVisibility(listBeen.size() > 0 ? View.VISIBLE : View.GONE);
                    }
                    isRequest = false;
                } else {
                    isRequest = true;
                    if (selectTag != null) {
                        HashSet<ResourceItemBean.DataBean.ListBean> listBeen = new HashSet<>(selectTag);
                        mConfirmBtn.setVisibility(listBeen.size() > 0 ? View.VISIBLE : View.GONE);
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("buId", buId); //   业务单位ID(必填)
                    bundle.putString("pbUkid", pbUkid); //  发布ukid
                    bundle.putString("rsName", ""); // 资源名称
                    bundle.putString("sort", mSort); //     排序(DESC,ASC)
                    bundle.putSerializable("selectTag", (Serializable) selectTag);
                    SetFragmentAndPage(dataBean.getTotal(), 5, new ReleaseGoodsListFragment().getClass().getName(), bundle);
                }
            } else {
                toast(commonClass.getMsg());
            }
        } else if (what == 1) {

            if (TextUtils.equals("0", commonClass.getCode())) {
                ContractCommon.getInstance().getPublishGoodsData().clear();
                toSettingRule();
                requestData();
            } else {
                toast(commonClass.getMsg());
            }
        } else if (what == 2) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                ResourceItemBean.DataBean dataBean = JSON.parseObject(commonClass.getData().toString(), ResourceItemBean.DataBean.class);
                if (dataBean.getTotal() == 0) {
                    ShowEmptyView();
                    mConfirmBtn.setVisibility(View.GONE);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("buId", buId); //   业务单位ID(必填)
                    bundle.putString("pbUkid", pbUkid); //  发布ukid
                    bundle.putString("rsName", text); // 资源名称
                    bundle.putString("sort", mSort); //     排序(DESC,ASC)
                    bundle.putSerializable("selectTag", (Serializable) selectTag);
                    SetFragmentAndPage(dataBean.getTotal(), 5, new ReleaseGoodsListFragment().getClass().getName(), bundle);
                }

            } else {
                toast(commonClass.getMsg());
            }
        }


    }

    @Override
    public void onDownPull() {
        if (isShow) {
            ((BaseCardDeskActivity) mActivity).hideFilterBt();
            ((BaseCardDeskActivity) mActivity).showSearchTitle();
        } else {
            ((BaseCardDeskActivity) mActivity).hideSearchTitle();
        }
        isShow = !isShow;
    }
}
